<template>
  <div>
    <n-card class="GoodsClassification__content">
      <n-button @click="handleCreate" type="info" large>添加分类</n-button>
      <br>
      <br>
      <n-data-table
        :columns="columns"
        :single-line="false"
        :data="goodsClassificationList"
        :row-key="rowKey"
        :pagination="pagination"
      >
      </n-data-table>
    </n-card>
  </div>
</template>
<script lang="ts">
import {NDataTable,NIcon,NCard,NButton,NTag,NDialog,NSpace,NForm,NFormItem,NInput,NTreeSelect} from 'naive-ui';
import {useDialog,useMessage} from 'naive-ui';
import {MdCheckmarkCircle} from '@vicons/ionicons4';
import { computed, h, reactive,ref } from 'vue';
export default {

components:{
  NDataTable,
  NIcon,
  NTag,
  NCard,
  NButton,
  MdCheckmarkCircle,
  NDialog,
  NSpace,
  NForm,
  NFormItem,
  NInput,
  NTreeSelect,
},


setup(){
  const message = useMessage();
  const dialog = useDialog();

  const change=ref(true);
  /**
   * 从localStorage获取数据
   */
  const goodsClassificationList=computed(()=>{
    if(change.value)
      changeData();
    change.value=false;
    return JSON.parse(localStorage.getItem('goodsClassificationList'))
  });

  /**
   * 定义表列名和格式
   */
  const columns=[
    {
      title:'#',
      width:"80",
      key:'index',
      render(row:object){
        if(row.level.length===0)
          return row.index+1;
      }
    },{
      title:'名称分类',
      key:'classifyName',
      width:"200",
      render(row:object){
        return h(
          "span",
          {
            style:{
              marginLeft:(row.level.length)*20+'px',
              // width:'10px'
            }
          },
          {default:()=>row.classifyName}
        )
      }
    },{
      title:'是否有效',
      key:'effective',
      render(row:object){
        return h(
          NIcon,{
            size:"12",
            color:"lightgreen",
          },
          {
              default:()=>h(
                MdCheckmarkCircle
              )
          }
        )
      }
    },{
      title:'分级',
      key:'level',
      render(row:object){
        if(row.level.length==1)
        {
          return h(
            NTag,{
              type:'warning',
            },{
              default:()=>"二级"
            }
          )
        }
        if(row.level.length==2)
        {
          return h(
            NTag,{
              type:'success',
            },{
              default:()=>"三级"
            }
          )
        }
        return h(
            NTag,{
              type:'info',
            },{
              default:()=>"一级"
            }
          )
      }
    },{
      title:'操作',
      key:'action',
      render(row:object){
        return h(
          NSpace,{
            justify:'center',
          },{
            default:()=>
                [
                  h(
                  NButton,
                  {
                    type:'info',
                    onclick:()=>{
                      inputValue.value=row.classifyName;
                      dialog.warning({
                      title:'编辑分类',
                      closable:false,
                      showIcon:false,
                      content:()=>{
                        return h(
                          NForm,
                          {
                            labelPlacement: 'left',
                          },{
                            default:()=>h(
                              NFormItem,{
                                label:'分类名称',
                              },{
                                default:()=>h(
                                  NInput,{
                                    placeholder:'',
                                    value:inputValue.value,
                                    onInput:(event:any)=>{
                                      inputValue.value=event;
                                    }
                                  },
                                )
                              }
                            )
                          }
                        )
                      },
                      positiveText: '确定',
                      negativeText: '取消',
                      onPositiveClick: () => {
                        editDataSource(row);
                      },onNegativeClick: () => {
                        message.error('取消了编辑操作')
                      }
                      })
                    }

                  },{
                    default:()=>'编辑'
                  }
                ),
                h(
                  NButton,
                  {
                    type:'error',
                    onclick:()=>{
                      dialog.warning({
                      title:'删除确认',
                      content:'此操作将删除该分类, 是否继续?',
                      positiveText: '确定',
                      negativeText: '取消',
                      onPositiveClick: () => {
                        deleteDataSource(row);
                      },onNegativeClick: () => {
                        message.error('取消了删除该分类操作')
                      }
                      })
                    }
                  },{
                    default:()=>'删除'
                  }
                ),
              ]
            
          }
        )
      }
    }
  ];
  /**
   * 改变主分类的索引
   */
  const changeData=()=>{
    let list=JSON.parse(localStorage.getItem('goodsClassificationList'));
    for(let i=0;i<list.length;i++)
    {
      list[i].index=i;
      if(list[i]["children"])
      {
        let levellist1=[i];
        for(let j=0;j<list[i].children.length;j++)
        {
          list[i].children[j].index=j;
          list[i].children[j]["level"]=levellist1;
          if(list[i].children[j]["children"])
          { 
            let levellist2=[i,j];
            for(let k=0;k<list[i].children[j].children.length;k++)
            {
              list[i].children[j].children[k].index=k;
              list[i].children[j].children[k].level=levellist2;
            }
          }
        }
      }
    }
    localStorage.setItem('goodsClassificationList',JSON.stringify(list));
  }

  /**
   * 创建分类
   */
  const handleCreate=()=>{
    inputValue.value='';
    dialog.warning({
      title:'添加分类',
      closable:false,
      showIcon:false,
      content:()=>{
        return h(
          NForm,
          {
            labelPlacement: 'left',
          },{
            default:()=>[h(
              NFormItem,{
                label:'分类名称',
              },{
                default:()=>h(
                  NInput,{
                    placeholder:'',
                    value:inputValue.value,
                    onInput:(event:any)=>{
                      inputValue.value=event;
                    }
                  },
                )
              }
            ),h(
              NFormItem,{
                label:'父级分类 ',
              },{
                default:()=>h(
                  NTreeSelect,
                  {
                    options:optionList.value,
                    placeholder:'请选择',
                    value:selectedValue.value,
                    'onUpdate:value':(value:any)=>{
                      selectedValue.value=value;
                    }
                  },{
                  }
                )
              }
            ),
            ]
          }
        )
      },
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        createDataSource();
      },onNegativeClick: () => {
        message.error('取消了添加分类操作')
      }
      })
  }
  const selectedValue=ref('');

  /**
   * 创建分类
   */
  const createDataSource=()=>{
    if(inputValue.value=='')
    {
      message.error('输入不能为空');
      return false;
    }
    let list=JSON.parse(localStorage.getItem('goodsClassificationList'));
    let option={
        id:(new Date().toString()+"l"),
        classifyName:inputValue.value,
        effective:true,
        staticProperties:[],
        dynamicProperties:[],
        staticPropertiesTags:{},
        dynamicPropertiesTags:{},
        level:[],}
    let strlist=selectedValue.value.split(" ");
    if(selectedValue.value==='')
    {
      list.push(option);
    }
    else if(strlist.length===1)
    {
      if(!list[strlist[0]].children)
      {
        list[strlist[0]].children=[];
      }
      list[strlist[0]].children.push(option);
    }
    else if(strlist.length==2)
    {
      if(!list[strlist[0]].children[strlist[1]].children)
      {
        list[strlist[0]].children[strlist[1]].children=[];
      }
      list[strlist[0]].children[strlist[1]].children.push(option);
    }
    localStorage.setItem('goodsClassificationList',JSON.stringify(list));
    change.value=true;
    selectedValue.value='';
    message.success('添加分类成功')
  }
  
  const optionList=computed(()=>{

    let list=JSON.parse(localStorage.getItem('goodsClassificationList'));
    if(change.value)
      list=JSON.parse(localStorage.getItem('goodsClassificationList'));
    let options: any[]=[];
    for(let i=0;i<list.length;i++)
    {
      options[i]=reactive<{}>({});
      options[i].label=list[i].classifyName;
      options[i].key=i+"";
      if(list[i]["children"])
      {
        options[i].children=[];
        for(let j=0;j<list[i].children.length;j++)
        {
          options[i].children[j]=reactive<{}>({});
          options[i].children[j].label=list[i].children[j].classifyName;
          options[i].children[j].key=i+" "+j;
        }
      }
    }
    change.value=false;
    return options;
  })

  const inputValue=ref('');
  /**
   * 编辑方法
   * params: row 一行的数据
   */
  const editDataSource=(row:object)=>{
    let list=JSON.parse(localStorage.getItem('goodsClassificationList'));
    if(row.level.length==0)
    {
      list[row.index].classifyName=inputValue.value;
    }
    if(row.level.length==1)
    {
      list[row.level[0]].children[row.index].classifyName=inputValue.value;
    }
    if(row.level.length==2)
    {
      list[row.level[0]].children[row.level[1]].children[row.index].classifyName=inputValue.value;
    }
    localStorage.setItem('goodsClassificationList',JSON.stringify(list));
    change.value=true;
    message.success('编辑该分类名称成功');
  }

  /**
   * 根据索引删除数据
   * params index 索引
   */
  const deleteDataSource=(row:object)=>{
    let list=JSON.parse(localStorage.getItem('goodsClassificationList'));
    if(row.level.length==0)
    {
      list.splice(row.index,1);
    }
    if(row.level.length==1)
    {
      list[row.level[0]].children.splice(row.index,1);
      if(list[row.level[0]].children.length==0)
      {
        delete list[row.level[0]].children;
      }
    }
    if(row.level.length==2)
    {
      list[row.level[0]].children[row.level[1]].children.splice(row.index,1);
      if(list[row.level[0]].children[row.level[1]].children.length==0)
      {
        delete list[row.level[0]].children[row.level[1]].children;
      }
    }
    localStorage.setItem('goodsClassificationList',JSON.stringify(list));
    change.value=true;
    message.success('删除该分类成功');
  }

  /**
   * 分页map
   */
  const pagination=reactive<{}>({
      page:1,
      pageSize:6,
      showSizePicker:true,
      pageSizes:[6,8,10],
      onChange:(page:number)=>{OnChange(page);},
      onPageSizeChange:(pageSize:any)=>{OnPageSizeChange(pageSize);}
    })
  /**
   * 改变页时的函数
   * params p 分页后的页值
   */
  const OnChange=(p:number)=>{
    pagination.page=p;
  }
  /**
   * 改变一页最大数量的函数
   * params ps 一页最大数量
   */
  const OnPageSizeChange=(ps:number)=>{
    pagination.pageSize=ps;
    pagination.page=1;
  }

  return {
    rowKey(row:object){return row.id},
    deleteDataSource,
    columns,
    goodsClassificationList,
    handleCreate, 
    changeData,
    inputValue,
    pagination,
  }
}
}
</script>

<style>

.GoodsCLassification__content{
  margin:24px 24px 24px;
  width: inherit;
  font-size:12px;
}

</style>
